var express = require('express');
var router = express.Router();
var db = require('../model/mysql');
var async = require('async');

/* GET home page. */
router.get('/lst/:id/:p', function(req, res, next) {
    var cat_id=req.params.id;
    var p=req.params.p;
    var pageSize=15;
    var totalPage=1;
    async.waterfall([
        function(cb){//获取总页数
            var sql='select count(*) counts from article where cat_id=?;';
            db.query(sql,[cat_id],function(err,rows){
                totalPage=parseInt(Math.ceil(parseInt(rows[0].counts)/pageSize));
                cb(err,totalPage);
            })
        },
        function(data,cb){  //先获取分页
            if(typeof(p)=='undefined' || p<=1){
              p=1;
            }else if(p>=data){
              p=data;
            }
            cb(null,p);
        },
        function(data,cb){ //获取数据
            var sql='select id,title,author,post_time from article where cat_id=? order by post_time desc limit '+(data-1)*pageSize+','+pageSize;
            db.query(sql,[cat_id],function(err,rows){
              cb(err,rows);
            })
        }
    ],function(err,results){
        res.render('article/lst', {catData:results,p:p,totalPage:totalPage,cat_id:cat_id});
    });
});
router.get('/single/:id', function(req, res, next) {
  var id = req.params.id;
  var sql = 'select * from article where id=?;';
  db.query(sql,[id],function(err,rows){
     res.render('article/single', {data:rows[0],cat_id:rows[0].cat_id});
  });
});

module.exports = router;
